<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      :before-close="handleClose"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="章节名称" prop="chapterName">
          <el-input v-model="dataForm.chapterName" placeholder="章节名称"></el-input>
        </el-form-item>
        <el-form-item label="章节编号" prop="chapterNo">
          <el-input v-model="dataForm.chapterNo" placeholder="章节编号"></el-input>
        </el-form-item>
        <el-form-item label="配置播放量" prop="chapterVisit">
          <el-input v-model.number="dataForm.chapterVisit" placeholder="配置播放量" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节音频" prop="sourceInfo.audio_url">
          <!-- <span v-if="dataForm.id">{{dataForm.sourceInfo.audio_url}}</span>
          <div v-if="dataForm.id">
            <div v-if="objaudio">
              <audio controls="controls" id="url">
                <source :src="dataForm.sourceInfo.audio_url" type="audio/mp3">
              </audio>
            </div>
            <span
              style="color:#00f;cursor: pointer; "
              @click="listen()"
            >{{dataForm.sourceInfo.audio_name}}</span>
            <br>
          </div>
          <div v-if="audios">
            <audio controls="controls" id="myaudio">
              <source :src="dataForm.sourceInfo.audio_url" type="audio/mp3">
            </audio>
            <span
              style="color:#00f;cursor: pointer; "
              v-if="listens"
              @click="listen()"
            >{{dataForm.sourceInfo.audio_name}}</span>
          </div> -->
          <audio controls="controls" v-if="dataForm.sourceInfo.audio_url!=''" id="myaudio"
                 :src="dataForm.sourceInfo.audio_url" type="audio/mp3"></audio>
          <div
            style="color:#00f;width: 100%;overflow: hidden; "
            v-if="dataForm.sourceInfo.audio_url!=''"
          >{{dataForm.sourceInfo.audio_name}}
          </div>
          <el-upload
            ref="replaceUploader"
            :file-list="replaceList"
            :action="url"
            :multiple="false"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :beforeUpload="beforeAvatarUpload"
            :on-remove="removefile"
            :on-change="handleChange"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="章节内容" prop="content" class="content">
          <template>
            <script :id="cueId" class="ueditor-box" type="text/plain">
  {{dataForm.content}}

            </script>
          </template>
        </el-form-item>
        <el-form-item label="视频时长" prop="video_duration" v-if="hasVideo==1">
          <el-input v-model="dataForm.video_duration" placeholder="例如: 00:40:41"></el-input>
        </el-form-item>
        <el-form-item label="上传视频" v-if="hasVideo==1">
          <video
            v-if="dataForm.sourceInfo.video_url"
            :src="dataForm.sourceInfo.video_url"
            style="width: 185px;"
            controls="controls"
            id="myvideo"
          >您的浏览器不支持视频播放
          </video>
          <div style="color:#00f;width: 100%;overflow: hidden; " v-if="dataForm.sourceInfo.video_url!=''">
            {{dataForm.sourceInfo.video_name}}
          </div>
          <el-upload
            ref="replaceUploader1"
            :file-list="replaceList1"
            :show-file-list="true"
            :action="videourl"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :on-remove="removefile1"
            :on-change="handleChange1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp4/video/ogg/flv/aviwmv/rmvb文件且大小不超过50M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频封面" v-if="hasVideo==1">
          <img v-if="dataForm.sourceInfo.cover_url" :src="dataForm.sourceInfo.cover_url" class="avatar">
          <el-upload
            :action="uploadUrl"
            :file-list="replaceList2"
            :show-file-list="true"
            :on-success="handleimgSuccess"
            :before-upload="beforeimgUpload"
            :on-remove="removefile2"
            :on-change="handleChange2"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview()">预览</el-button>
        <el-button @click="down()">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="qrcode" width="30%">
      <div class="qrcode">
        <img :src="qrimg">
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .ueditor-box {
    height: 150px;
    // width: 60%;
  }
  .qrcode {
    width: 200px;
    height: 200px;
    margin: 0 auto;
  }
  .qrcode img {
    width: 100%;
    height: 100%;
  }
  .content {
    height: 590px !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
  import ueditor from "ueditor";

  export default {
    data() {
      return {
        visible: false,
        audios: false,
        objaudio: false,
        listens: true,
        qrcode: false,
        dataForm: {
          id: 0,
          video_duration: '',
          bookId: "",
          chapterNo: "",
          chapterName: "",
          sourceInfo: {
            audio_url: "",
            audio_name: "",
            audio_time: "",
            video_url: "",
            video_name: '',
            cover_url: '',//视频封面URL
            cover_name: '',
          },
          content: "",
          wordNumber: "",
          chapterVisit: ""
        },
        dataRule: {
          chapterNo: [
            {required: true, message: "章节编号不能为空", trigger: "blur"}
          ],
          chapterName: [
            {required: true, message: "章节名称不能为空", trigger: "blur"},
            {max: 18, message: "最长18个字符", trigger: "blur"}
          ],
          chapterVisit: [
            {required: true, message: "配置播放量不能为空", trigger: "blur"},
            {type: "number", message: "请输入数字", trigger: "blur"}
          ],
          video_duration: [
            {required: true, message: "视频时长不能为空", trigger: "blur"},
            {
              pattern: /\d{2}:\d{2}:\d{2}/,
              message: "请输入正确格式",
              trigger: "blur"
            }
          ]
        },
        url: "",
        ue: null,
        cueId: `J_ueditorBox_${new Date().getTime()}`,
        ueContent: "",
        replaceList: [],
        replaceList1: [],
        replaceList2: [],
        qrimg: "", //二维码
        getQr: "",
        videourl: "", //视频url
        imageUrl: '',//图片路径
        hasVideo: "",//判断是否有视频
        uploadUrl: "",//上传图地址
      };
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/course/bookchapter/upload?token=${this.$cookie.get("token")}`
      );
      this.videourl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideo?token=${this.$cookie.get("token")}`
      );
      this.uploadUrl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideoCover?token=${this.$cookie.get("token")}`
      );
    },
    methods: {
      // 关闭窗口音频就关闭
      handleClose() {
        let that = this;
        this.visible = false;
        var myAuto =
          document.getElementById("myaudio");

        console.log(this.dataForm.sourceInfo.coverUrl)
        // var myvideo =  document.getElementById("myvideo")
        if (myAuto) {
          myAuto.pause();
          myAuto.load();
          that.ue.execCommand("cleardoc");
        } else {
          that.ue.execCommand("cleardoc");
        }
      },
      // 预览
      preview() {
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
        });
        this.getQr = this.ueContent.replace(
          /<img/g,
          "<img style='width:100%;height:auto'"
        );
        let audio = ''
        let video = ''
        if (this.dataForm.sourceInfo.video_url) {
          video = `<div><video
            src="${this.dataForm.sourceInfo.video_url}"
            poster="${this.dataForm.sourceInfo.cover_url}"
            style="width: 100%;"
            controls="controls"
          ></video></div>`
        }
        if (this.dataForm.sourceInfo.audio_url) {
          audio = `<div><div style="position: fixed;width: 100%;height: 120px;top: 0;left: 0;background: #fff;z-index:99;">
<div style="display: flex;">
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;background: #17B3A3;color: #fff;" onclick="setspeed(this,1)">1倍</div>
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;" onclick="setspeed(this,1.5)">1.5倍</div>
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;" onclick="setspeed(this,2)">2倍</div></div>
<audio id="audiodom" controls="controls" style="width: 100%;" src="${this.dataForm.sourceInfo.audio_url}" />
</div>
<div style="margin-top: 130px;"></div>`
        }
        let script = `\<script\>
function setspeed(self,speed){
let btn = document.getElementsByClassName('btn')
for(let i=0;i<btn.length;i++){
btn[i].style.background='#fff'
btn[i].style.color='#000'
}
self.style.background = '#17B3A3'
self.style.color = '#fff'
document.getElementById('audiodom').playbackRate = speed
}
\<\/script\>`
        this.$http({
          url: this.$http.adornUrl("/course/bookchapter/getQr"),
          method: "post",
          data: this.$http.adornData({
            content: audio + video + this.getQr+script
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.qrcode = true;
            this.qrimg = data.qrUrl;
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      // 取消按钮音频就关闭并且富文本清空
      down() {
        let that = this;
        this.visible = false;
        var myAuto = document.getElementById("myaudio");
        this.dataForm.sourceInfo.coverUrl = "";
        // var myvideo =  document.getElementById("myvideo")[0]
        if (myAuto) {
          myAuto.pause();
          myAuto.load();
          // myvideo.pause();
          that.ue.execCommand("cleardoc");
          this.objaudio = false;
        } else {
          that.ue.execCommand("cleardoc");
          this.objaudio = false;
        }
      },
      listen() {
        this.objaudio = true;
      },
      // 移除音频
      removefile() {
        this.dataForm.sourceInfo.audio_url = "";
      },
      removefile1() {
        this.dataForm.sourceInfo.video_url = "";
      },
      removefile2() {
        this.dataForm.sourceInfo.cover_url = "";
      },
      init(data) {
        this.hasVideo = data.hasVideo
        setTimeout(() => {
          this.ue = ueditor.getEditor(this.cueId, {
            // serverUrl: '', // 服务器统一请求接口路径
            zIndex: 3000
          });
        }, 100);
        this.dataForm.id = data.id || 0;
        if (data.bookId) {
          this.dataForm.bookId = data.bookId;
          // alert(bookId)
        }

        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          this.$refs.replaceUploader.clearFiles();
          if (this.hasVideo == 1) {
            this.$refs.replaceUploader1.clearFiles();
          }
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookchapter/info/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.bookId = data.bookChapter.bookId;
                this.dataForm.chapterNo = data.bookChapter.chapterNo;
                this.dataForm.chapterName = data.bookChapter.chapterName;
                this.dataForm.chapterDesc = data.bookChapter.chapterDesc;
                this.dataForm.sourceInfo = data.bookChapter.sourceInfo;
                this.dataForm.wordNumber = data.bookChapter.wordNumber;
                this.dataForm.chapterVisit = data.bookChapter.chapterVisit;
                this.dataForm.sourceInfo = JSON.parse(this.dataForm.sourceInfo);
                if (this.dataForm.sourceInfo && this.dataForm.sourceInfo.video_duration) {
                  const duration = this.dataForm.sourceInfo.video_duration / 1000
                  const hour = parseInt(duration / 3600) < 10 ? '0' + parseInt(duration / 3600) : parseInt(duration / 3600)
                  const minute = parseInt(duration % 3600 / 60) < 10 ? '0' + parseInt(duration % 3600 / 60) : parseInt(duration % 3600 / 60)
                  const second = parseInt(duration % 60) < 10 ? '0' + parseInt(duration % 60) : parseInt(duration % 60)
                  this.dataForm.video_duration = `${hour}:${minute}:${second}`
                }
                this.dataForm.content = data.bookChapter.content;
                this.ue.ready(() => {
                  this.ue.setContent(this.dataForm.content);
                });
              }
            });
          }
        });
      },
      handleAvatarSuccess(response, file, fileList) {
        this.replaceList = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.sourceInfo.audio_url = response.url;
          this.dataForm.sourceInfo.audio_name = file.name;
          this.audios = true;
          this.objaudio = false;
          this.listens = false;
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传音频
      beforeAvatarUpload(file) {
        this.objaudio = false;
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);

        const extension = testmsg === "mp3";
        if (!extension) {
          this.$message({
            message: "上传文件只能是mp3格式！",
            type: "error"
          });
        } else {
          // 移除音频以便重新加载音频文件
          this.removefile();
        }
        return extension;
      },
      // 改变上传的时候取最后一个，实现替换上传
      handleChange(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList = [];
        this.replaceList.push(aa);
      },
      handleChange1(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList1 = [];
        this.replaceList1.push(aa);
      },
      handleChange2(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList2 = [];
        this.replaceList2.push(aa);
      },
      //上传视频
      beforeUploadVideo(file) {
        this.dataForm.sourceInfo.video_size = file.size;
        const isLt50M = file.size / 1024 / 1024 > 50;
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb"
          ].indexOf(file.type) == -1
        ) {
          this.$message.error("请上传正确的视频格式");
          return false
        } else if (isLt50M) {
          this.$message.error("请上传的视频小于50M");
          return false
        } else {
          this.removefile1();
        }
      },
      //视频上传成功
      handleVideoSuccess(response, file, fileList) {
        this.replaceList1 = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.sourceInfo.video_url = response.videoUrl;
          this.dataForm.sourceInfo.video_name = response.videoName;
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传视频封面
      handleimgSuccess(res, file) {
        this.dataForm.sourceInfo.cover_url = res.coverUrl;
        this.dataForm.sourceInfo.cover_name = res.coverName;
      },
      beforeimgUpload(file) {
        const isType = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isType) {
          this.$message.error('上传封面图片只能是 png/jpg/jpeg 格式!');
        } else {
          this.removefile2();
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        const isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = Math.round(img.width / img.height) == 2;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的视频封面必须是16:9!");
            return Promise.reject();
          }
        );
        return isType && isSize && is250K
      },
      // 表单提交
      getContent(res, file) {
        if (this.hasVideo == 1) {
          const durationArr = this.dataForm.video_duration.split(':')
          this.dataForm.sourceInfo.video_duration = durationArr[0] * 60 * 60 * 1000 + durationArr[1] * 60 * 1000 + durationArr[2] * 1000
          if (!this.dataForm.sourceInfo.video_url) {
            this.$message({
              message: '请上传视频',
              type: 'warning'
            })
            return
          }
          if (!this.dataForm.sourceInfo.cover_url) {
            this.$message({
              message: '请上传视频封面',
              type: 'warning'
            })
            return
          }
        }
        // 获取音频时长
        // 这里加了下判断，是在修改的时候修改其他字段不改这个音频也不会报错
        if (
          document.getElementById("myaudio") ||
          document.getElementById("url")
        ) {
          this.dataForm.sourceInfo.audio_time =
            document.getElementById("myaudio").duration * 1000 ||
            document.getElementById("url").duration * 1000;
        }
        let that = this;
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
        });
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookchapter/${!this.dataForm.id ? "save" : "update"}`
              ),
              method: "post",
              data: this.$http.adornData({
                bookId: this.dataForm.bookId,
                chapterNo: this.dataForm.chapterNo,
                chapterName: this.dataForm.chapterName,
                sourceInfo: JSON.stringify(this.dataForm.sourceInfo),
                content: this.ueContent,
                chapterVisit: this.dataForm.chapterVisit,
                id: this.dataForm.id || undefined
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList", this.dataForm.bookId);
                  }
                });
                that.ue.execCommand("cleardoc");
                this.audios = false;
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      }
    }
  };
</script>
